'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
	//生成随机唯一id
	function randomId(number) {
		return Number(Math.random().toString().substr(3, number) + Date.now()).toString()
	}
	//event为客户端上传的参数
	const {
		userId,
		articleId,
		commentData,
		comment_id = '',
		is_reply = false,
		reply_id = '',
	} = event
	//获取用户
	let user = await db.collection("user").doc(userId).get();
	user = user.data[0]

	//获取文章
	const GetArticle = await db.collection("article").doc(articleId).get();
	let comments_count = GetArticle.data[0].comments_count; //获取评论数量
	const comments = GetArticle.data[0].comments; //获取文章所有评论Arr
	//需要插入的信息
	let commentObj = {
		comment_id: randomId(5),
		comment_content: commentData,
		create_time: Date.now(),
		is_reply,
		replyArr: [],
		author: {
			author_id: user._id,
			author_name: user.author_name,
			avatar: user.avatar,
			professional: user.professional
		}
	}
	if (comment_id === '') {
		//文章主评论处理
		commentObj.replyArr = [];
		commentObj = dbCmd.unshift(commentObj);
	} else {
		/*评论回复处理*/
		//获取当前评论集合，找到指定评论，修改replyArr属性
		let authorName = null;
		let commentsIndex = comments.findIndex(item => item.comment_id === comment_id); //获取当前评论下标
		if (is_reply) {
			//指定用户回复
			authorName = comments[commentsIndex].replyArr.find(item => item.comment_id === reply_id).author
				.author_name; //获取回复用户名
		} else {
			//主评论回复
			authorName = comments.find(item => item.comment_id === comment_id).author.author_name; //获取回复用户名
		}

		commentObj.ago = authorName;
		commentObj = {
			//插入到当前下标的回复内容数组中
			[commentsIndex]: {
				replyArr: dbCmd.unshift(commentObj)
			}
		}
	}

	comments_count = comments_count + 1 //评论数加一
	await db.collection("article").doc(articleId).update({
		comments: commentObj,
		comments_count
	})

	//返回数据给客户端
	return {
		code: 0,
		data: {
			msg: "添加评论成功"
		}
	}
};
